package com.ygqh.baby.service.wechat.api;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.mp.api.MpApi;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.ygqh.baby.service.wechat.model.good.GoodImportOrderRequestParam;
import com.ygqh.baby.service.wechat.model.good.GoodImportOrderResult;
import com.ygqh.baby.service.wechat.model.good.GoodImportProductRequestParam;
import com.ygqh.baby.service.wechat.model.good.GoodImportProductResult;

/**
 * 好物圈API
 *
 * @Author: sunshuo
 * @Date: 2019/5/21 17:01
 * @Version: 1.0
 */
public class GoodApi extends MpApi {

	private final TokenHolder tokenHolder;

	public GoodApi(TokenHolder tokenHolder) {
		this.tokenHolder = tokenHolder;
	}

	/**
	 * 导入订单
	 *
	 * @param requestParam 请求参数
	 * @throws WeixinException
	 */
	public GoodImportOrderResult importOrder(GoodImportOrderRequestParam requestParam)
			throws WeixinException {
		requestParam.validateRequestParamForImportOrder();
		String requestUrl = String.format(requestParam.getRequestUri(),
				requestParam.getAction().getValue(), requestParam.getIsHistory(), tokenHolder.getAccessToken());
		JSONObject body = new JSONObject(1);
		body.put("order_list", requestParam.getOrderList());
		WeixinResponse response = weixinExecutor.post(requestUrl, body.toJSONString());
		return response.getAsObject(new TypeReference<GoodImportOrderResult>() {
		});
	}

	/**
	 * 导入物品
	 *
	 * @param requestParam 请求参数
	 * @return
	 * @throws WeixinException
	 */
	public GoodImportProductResult importProduct(GoodImportProductRequestParam requestParam) throws WeixinException {
		requestParam.validateRequestParamForImport();
		String requestUrl = String.format(requestParam.getRequestUri(), tokenHolder.getAccessToken());
		JSONObject body = new JSONObject(1);
		body.put("product_list", requestParam.getProductList());
		WeixinResponse response = weixinExecutor.post(requestUrl, body.toJSONString());
		return response.getAsObject(new TypeReference<GoodImportProductResult>() {
		});
	}
}
